<template>
  <div class="h-full p-2">
    <Scrollbar>
      <Tabs v-model:activeKey="activeKey" type="card" centered>
        <TabPane key="1" tab="名称">
          <Card
            title="查询名称"
            :bordered="false"
            :body-style="bodyStyle"
            :head-style="headStyle"
            class="_card"
          >
            <Input v-model:value="dataRef.queryName"
          /></Card>
          <Card :bordered="false" :body-style="bodyStyle" :head-style="headStyle" class="_card">
            <template #title>
              字段合计 <a-button type="primary" @click="handleAddField" size="small">新增</a-button>
            </template>
            <TotalField
              ref="totalFieldRef"
              :formCode="dataRef.formCode"
              v-model:model-value="dataRef.stateDesc"
          /></Card>
          <Card
            title="流程"
            :bordered="false"
            :body-style="bodyStyle"
            :head-style="headStyle"
            class="_card"
          >
            <div class="flex items-center gap-5px mb-2">
              <div style="width: 56px">状态</div>
              <Select :options="statusOptions" style="flex: 1" v-model:value="dataRef.flowStatus" />
            </div>
            <div class="flex items-center gap-5px">
              <div style="width: 56px">开始时间</div>
              <RangePicker
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="flex: 1"
                v-model:value="dates"
                @change="getDatesChange"
              />
            </div>
          </Card>
          <Card
            :bordered="false"
            title="主表关联查询"
            :body-style="bodyStyle"
            :head-style="headStyle"
            class="_card"
          >
            <Select
              :options="queryGetMainFormQuery"
              show-search
              optionFilterProp="label"
              style="width: 100%"
              v-model:value="dataRef.queryRelated"
            />
          </Card>
          <Card title="数据表" :bordered="false" :body-style="bodyStyle" :head-style="headStyle">
            <InputSearch
              v-if="!currentRecord.code"
              style="margin: 0 5px 5px 0"
              placeholder="请输入查询"
              v-model:value="selectedValue"
              @search="onSearch"
              @change="onChange"
            />
            <div class="flex-auto pr-1 mb-2 overflow-y-scroll">
              <ul>
                <li
                  v-if="currentRecord.code"
                  class="p-1 mb-1 overflow-hidden cursor-pointer source-componet-item source-componet-item-selected"
                >
                  {{ currentRecord.name }}
                </li>
                <li
                  v-else
                  class="p-1 mb-1 overflow-hidden cursor-pointer source-componet-item"
                  v-for="(item, index) in moduleList"
                  :key="index"
                  @click="handleClick(item)"
                  :class="{ 'source-componet-item-selected': currentRecord.code == item.code }"
                >
                  {{ item.name }}
                </li>
              </ul>
            </div>
          </Card>
        </TabPane>
        <TabPane key="2" tab="排序">
          <div
            v-for="item in dataRef.order"
            :key="item.code"
            class="flex items-center w-4/5 m-auto mb-2"
          >
            <div style="flex: 1">{{ item.title }}</div>
            <div>
              <Select
                :options="orderFieldCodeOptions"
                style="width: 100px"
                v-model:value="item.orderFieldCode"
              />
            </div>
          </div>
        </TabPane>
      </Tabs>
    </Scrollbar>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, watch, nextTick } from 'vue';
  import { Scrollbar } from '/@/components/Scrollbar';
  import { Tabs, TabPane, Card, Input, Select, RangePicker, InputSearch } from 'ant-design-vue';
  import { statusOptions, bodyStyle, headStyle, orderFieldCodeOptions } from './fieldEdit.data';
  import TotalField from './TotalField.vue';
  import { getModulesAll } from '/@/api/system/system';
  import { getQueryGetMainFormQuery } from '/@/api/reportForms/reportForms';
  import { useDebounceFn } from '@vueuse/core';
  import { cloneDeep } from 'lodash-es';
  import { isArray } from '/@/utils/is';
  const props = defineProps({
    formGetFieldsData: {
      type: Array,
      default: () => [],
    },
    fieldEditData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  const emit = defineEmits(['change-form-code']);
  const activeKey = ref('1');
  const dates = ref<any>([]);
  const dataRef = ref<Recordable>({
    flowStatus: '',
    formCode: '',
    order: [],
    queryName: '',
    queryRelated: '',
    stateDesc: {},
    beginDate: '',
    endDate: '',
  });

  //日期值
  const getDatesChange = (val) => {
    console.log('val', val);
    if (val && val.length) {
      const [beginDate, endDate] = val;
      dataRef.value.beginDate = beginDate;
      dataRef.value.endDate = endDate;
    } else {
      dataRef.value.beginDate = '';
      dataRef.value.endDate = '';
    }
  };

  const totalFieldRef = ref<any>(null);
  //字段合计新增
  const handleAddField = () => {
    totalFieldRef.value.handleCreate();
  };
  //主表关联查询选择
  const queryGetMainFormQuery = ref<Recordable[]>([]);
  const getQueryGetMainFormQueryData = async () => {
    if (!dataRef.value.formCode) {
      return;
    }
    try {
      queryGetMainFormQuery.value =
        (await getQueryGetMainFormQuery({
          formCode: dataRef.value.formCode,
        })) || [];
      queryGetMainFormQuery.value.forEach((item) => {
        item.label = item.name;
        item.value = item.id.toString();
      });
    } catch (error) {}
  };

  const currentRecord = ref<Recordable>({});
  //模块
  const moduleList = ref<Recordable[]>([]);
  const oldModuleList = ref<Recordable[]>([]);
  const getModulesAllData = async () => {
    moduleList.value = (await getModulesAll()) || [];
    moduleList.value = moduleList.value.filter((item) => !!item.name);
    oldModuleList.value = cloneDeep(moduleList.value);
  };
  const handleClick = (record) => {
    console.log(record);
    currentRecord.value = record;
    dataRef.value.formCode = record.code;
    emit('change-form-code', dataRef.value.formCode);
  };

  //查询字段
  const selectedValue = ref(''); //查询字段
  const handleSearch = (val) => {
    console.log(val);
    if (val) {
      moduleList.value = oldModuleList.value.filter((item) => item.name.includes(val));
    } else {
      moduleList.value = [...oldModuleList.value];
    }
  };
  const onSearch = useDebounceFn(handleSearch, 300);

  const onChange = (e) => {
    onSearch(e.target.value);
  };

  //   onMounted(() => {
  //     getModulesAllData();
  //   });
  defineExpose({
    dataRef,
  });
  watch(
    () => props.fieldEditData,
    (newVal) => {
      nextTick(async () => {
        await getModulesAllData();
        dataRef.value = newVal;
        if (!isArray(dataRef.value.order)) {
          dataRef.value.order = [];
        } else {
          dataRef.value.order.forEach((item) => {
            item.orderFieldCode = item.orderFieldCode ? item.orderFieldCode : '';
          });
        }
        if (dataRef.value.beginDate && dataRef.value.endDate) {
          dates.value = [dataRef.value.beginDate, dataRef.value.endDate];
        } else {
          dates.value = [];
        }
        if (dataRef.value.formCode) {
          // {name:'',code:''}
          currentRecord.value =
            moduleList.value.find((item) => item.code == dataRef.value.formCode) || {};
        } else {
          currentRecord.value = {};
        }
        getQueryGetMainFormQueryData();
        console.log('currentRecord.value', currentRecord.value);
        console.log('fieldEdit-dataRef.value', dataRef.value);
      });
    },
    {
      immediate: true,
    },
  );
</script>
<style lang="less" scoped>
  :deep(.ant-card-head-title) {
    padding: 0 5px;
  }
  ._card {
    margin-bottom: 10px;
  }
  .source-componet-item,
  .source-componet-item-title {
    border: 1px solid #d9d9d9;
    padding: 8px 10px;
    border-radius: 4px;
  }
  .source-componet-item:hover {
    border-color: #0960bd;
    color: #0960bd;
    background-color: rgba(9, 96, 189, 0.06);
  }
  .source-componet-item-selected {
    border-color: #0960bd;
    color: #0960bd;
    background-color: rgba(9, 96, 189, 0.06);
  }
</style>
